define(["angularAMD", "moment"], function (angularAMD, moment) {
        angularAMD.service('B0211Service', ['$rootScope', '$filter', '$translate', 'config', 'MMWService', '$mdDialog', '$mddProvider',
                function ($rootScope, $filter, $translate, config, $MMWService, $mdDialog, $mddProvider) {
                        this.init = function (machine, feedback) {
                                var nowdatetime = $filter('date')(new Date(), 'yyyy/MM/dd HH:mm:ss');
                                // 20230807 delete by wenwei for M#141950 设备故障状态修改故障原因报错
                                var dialogOpen = function (status_item, currentResion) {
                                     $mddProvider.UseForm('B0211', () => {
                                      $mdDialog.dialog(
                                          'module/moduleB/program/B02/B0211/B0211.html',
                                           function (dialog) {
                                             return {
                                               css_url: 'module/moduleB/program/B02/B0211/B0211.css',
                                               machine: machine,
                                               status_item: status_item,
                                               remark: '',
                                               remark_name:currentResion ? currentResion: '',
                                               maintain_order_list: [],
                                               handle_user_no: config.cache.account,
                                               _no: '',
                                               currentStatus: true,
                                               flag: true,
                                               _event: {
                                                 'handle_user_no':{
                                                     click: () => {
                                                         dialog.loadHandleUserNoList();
                                                     }
                                                  },
                                                  'remark_name': {
                                                      click: () => {
                                                       dialog.changeRemark();
                                                      }
                                                   }                                                 
                                                },
                                                 _fn:{
                                                    'Execute':{
                                                       click: () => {
                                                        dialog.confirm();
                                                      }
                                                    }
                                                  },
                                                 plan_start_time: [nowdatetime.split(' ')[0], nowdatetime.split(' ')[1]],
                                                 beforeShown: function () {
                                                    if (machine.machine_status == '3') {
                                                         maintainOrderInfoGet(function (data) {
                                                            dialog.maintain_order_list = data.maintain_order_list || [];
                                                            });
                                                     }
                                                 },
                                                 showMaintainOrder: function () {
                                                    return (dialog.machine.machine_status == '3' && dialog.maintain_order_list.length > 0);
                                                 },
                                                changeStatus: function (status) {                                                        
                                                        dialog.flag = false;
                                                        dialog.machine_status = status.code;
                                                        dialog.have_reason = status.have_reason;
                                                        dialog.require_reason = status.require_reason;
                                                        dialog.remark = '';
                                                        dialog.remark_name = '';
                                                        // 20231114 modify by shiwl for M#0134760: [sMES]H5的設備稼動選擇稼動選項時，保養、暫停、設置都未自動彈出原因，唯獨只有故障選項會自動彈出原因[宇榮/宇泰]
                                                        if (status.code == '5' || status.code == '3' ||status.code == '2' || status.code =='7' || status.code =='6') {
                                                                dialog.changeRemark();
                                                        }
                                                },
                                                changeRemark: function () {
                                                    var value_types = { '2': 'DOWN', '6': 'REPAIR', '3': 'MAINTAIN', '7': 'SETUP', '5': 'SUSPEND' };
                                                   //20221114 modify by shiwl for M#18991
                                                    var value = value_types[dialog.machine_status] ? value_types[dialog.machine_status] : value_types[machine.machine_status];
                                                    if (value == undefined)
                                                         value = 'DOWN';
                                                         //20190705 modify by Dustdusk for M#59591:
                                                         var open_select = function (items) {
                                                                 $rootScope.showSelect({
                                                                    label: function (item) {
                                                                            return item.page_name + '(' + item.page_no + ')';
                                                                    },
                                                                    code: 'page_no',
                                                                    selectCode: dialog.remark,
                                                                    list: items,
                                                                    confirm: function (item, radio_dialog) {
                                                                            radio_dialog.hide();
                                                                            dialog.remark = item.page_no;
                                                                            dialog.remark_name = item.page_name;
                                                                    }
                                                                 });
                                                         }
                                                         equipment_reason_get(value, machine.machine_no, function (items) {
                                                                 if (items.length == 0)
                                                                         equipment_reason_get(value, undefined, open_select);
                                                                 else
                                                                         open_select(items);
                                                         });
                                                       },
                                                       openMaintainOrder: function () {
                                                          $mdDialog.serviceDialog('B0232Service', {
                                                                  machine_no: dialog.machine.machine_no,
                                                                  maintain_order_list: dialog.maintain_order_list,
                                                                  callback: function () {
                                                                    dialog.beforeShown();
                                                                  }
                                                          });
                                                       },
                                                       back: function () {
                                                         dialog.hide();
                                                       },
                                                       //20170516 modify by Dustdusk for 修正故障原因未輸入的卡控
                                                       confirm: function () {
                                                         if (!dialog.machine.machine_no) {
                                                                 $rootScope.showAlert($filter('translate')('B0211.showAlert.column1'));
                                                         } else if (dialog.require_reason == '1' && dialog.remark == '') {
                                                                 $rootScope.showAlert($filter('translate')('B0211.showAlert.column3'));
                                                         } else {
                                                                                        // 20200623 modify by linzh for M#71452 - 使用日期套件更換日期，會強制轉為 GMT 時間格式，所以需要再轉換一次。
                                                              var work_time = $filter('date')(dialog.plan_start_time[0], 'yyyy/MM/dd') + " " + dialog.plan_start_time[1];
                                                              var content = {
                                                                      machine_no: dialog.machine.machine_no,
                                                                      report_datetime: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
                                                                      machine_status: dialog.machine_status ? dialog.machine_status : dialog.machine.status,
                                                                      remark: dialog.remark,
                                                                      handle_user_no: dialog.handle_user_no,
                                                                      plan_start_time: dialog.machine_status == '0' || dialog.machine_status == '1' ? '' : work_time,
                                                                      actual_end_time: dialog.machine_status == '0' || dialog.machine_status == '1' ? work_time : '',
                                                                      remarks: dialog.remarks
                                                               };
                                                              changeMachineStatusProcess(content, dialog);
                                                           }
                                                       },
                                                       //20200611 add by linzh for M#71452
                                                       loadHandleUserNoList: function () {
                                                         //20200623 modify by linzh for M#71452 取得用户资料
                                                         $MMWService.showQueryListPNIG({
                                                                 form_name:"PageNo_119",
                                                                 pageRecord: 50,
                                                                 condition: [
                                                                         { name: $filter('translate')('common.queryList.employee_c'), column_name: 'UserNo', query_mode: '2', value: dialog.handle_user_no }
                                                                 ],
                                                                 header: [
                                                                         { label: $filter('translate')('common.queryList.employee_c'), code: 'user_no' },
                                                                         { label: $filter('translate')('common.queryList.employee_n'), code: 'user_name' }
                                                                 ],
                                                                 setCondition: function (conditions) {
                                                                         conditions.push(
                                                                                 { column_name: 'IssueState', query_mode: '0', value: '2', merge_condition_model: 'AND' }
                                                                         );
                                                                         return conditions;
                                                                 },
                                                                 selectCode: dialog.handle_user_no || '',
                                                                 confirm: function (selectItem, dialog2) {
                                                                         dialog.handle_user_no = selectItem.user_no;
                                                                         dialog2.hide();
                                                                 }
                                                           });
                                                       }
                                                     };
                                                 }
                                                )
                                        })
                                }
                                // 保養單資訊取得
                                function maintainOrderInfoGet(callback) {
                                        var content = {
                                                machine_no: machine.machine_no
                                        };
                                        $MMWService.sendToServer({
                                                uri: 'ServicesSTD.Module_EQP.maintain_order_info_get',
                                                content: content,
                                                success: function (data) {
                                                        if (callback)
                                                         callback(data);
                                                }
                                        })
                                 }
                                 function changeMachineStatusProcess(content, dialog) {

                                        $MMWService.sendToServer({
                                                uri: 'ServicesSTD.Module_EQP.edit_machine_state_process',
                                                content: content,
                                                success: function (data) {
                                                        $rootScope.showToast($filter('translate')('B0211.showAlert.column4'));
                                                        dialog.hide();
                                                        if (feedback)
                                                                feedback();
                                                }
                                        });
                                }

                                //20190705 modify by Dustdusk for M#59591:
                                function equipment_reason_get(type, machine_no, callback) {
                                        var query_condition_info = [
                                                { column_name: 'REASONTYPE', query_mode: '0', merge_condition_model: 'AND', value: '6' },
                                                { column_name: 'REASONSUBTYPE', query_mode: '0', merge_condition_model: 'AND', value: type },
                                                { column_name: 'a.Equipment', query_mode: '0', merge_condition_model: 'AND', value: machine_no }
                                        ];
                                        // if(machine_no!= undefined)
                                        // query_condition_info.push({column_name:'a.Equipment', query_mode:'0', merge_condition_model:'AND', value: machine_no });
                                        $MMWService.pageNumberInfoGet({
                                                form_name:"PageNo_62",
                                                query_condition_info: query_condition_info
                                        }, function (items) {
                                                if (typeof (callback) == 'function')
                                                        callback(items);
                                        });
                                }

                           (function machineStatusGet() {
                               $MMWService.sendToServer({
                                   uri : 'ServicesSTD.Module_EQP.machine_status_info_get',
                                   content: {machine_no:machine.machine_no},
                                   success: function (data) {
                                       if(data.machine_status_get_detail.length>0){
                                           machine.machine_status = data.machine_status_get_detail[0].status;
                                           machine.machine_runtime = data.machine_status_get_detail[0].machine_runtime;
                                            // 设置默认原因状态  20221111 modify by shiwl for M#18991:
                                            var value_types = {'2' :'DOWN', '6':'REPAIR', '3': 'MAINTAIN', '7': 'SETUP', '5':'SUSPEND'};
                                            var value = value_types[machine.machine_status];
                                            let currentResion='';
                                            equipment_reason_get(value, data.machine_status_get_detail[0].machine_no,function(item){
                                                   item.forEach(element => {
                                                     if( element.page_no ==data.machine_status_get_detail[0].remark){
                                                        currentResion = element.page_name;    
                                                      }
                                                   });
                                                   dialogOpen(data.machine_status_get_detail[0].allow_status_detail,currentResion);
                                            });
                                       }
                                   }
                               });
                           })();
                        };
                }]);
});
